#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>

const int N = 50005;
int n, m, cnt, tot, scc[N];
int dfn[N], low[N], dis[N], in[N];
bool ins[N];
std::stack<int> stk;
std::queue<int> q;

struct Edge {
  int v, nxt, c;
};
struct Gragh {
  int e_cnt, heads[N];
  Edge e[N << 1];
  inline void add(int u, int v, int c) {
    e[++e_cnt].v = v, e[e_cnt].nxt = heads[u], heads[u] = e_cnt, e[e_cnt].c = c;
  }
} E, G;

void tarjan(int x) {
  dfn[x] = low[x] = ++cnt;
  ins[x] = true;
  stk.push(x);
  for (int i = E.heads[x]; i; i = E.e[i].nxt) {
    int v = E.e[i].v;
    if (!dfn[v]) {
      tarjan(v);
      low[x] = std::min(low[x], low[v]);
    } else if (ins[v]) {
      low[x] = std::min(low[x], dfn[v]);
    }
  }
  if (dfn[x] == low[x]) {
    ++tot;
    int tmp;
    do {
      tmp = stk.top();
      stk.pop();
      ins[tmp] = false;
      scc[tmp] = tot;
    } while (tmp != x);
  }
}

int main() {
#ifndef ONLINE_JUDGE
#ifdef LOCAL
  freopen("testdata.in", "r", stdin);
  freopen("testdata.out", "w", stdout);
#endif
#ifndef LOCAL
  freopen("message.in", "r", stdin);
  freopen("message.out", "w", stdout);
#endif
#endif

  while (true) {
    scanf("%d%d", &n, &m);
    if (n == 0 && m == 0) break;
    int x, y, c;
    for (int i = 1; i <= m; ++i) {
      scanf("%d%d%d", &x, &y, &c);
      E.add(x, y, c);
    }
    for (int i = 0; i < n; ++i) {
      if (!dfn[i]) tarjan(i);
    }
    for (int i = 0; i < n; ++i) {
      for (int j = E.heads[i]; j; j = E.e[j].nxt) {
        int v = E.e[j].v;
        if (scc[i] != scc[v]) {
          G.add(scc[i], scc[v], E.e[j].c);
          ++in[scc[v]];
        }
      }
    }
    memset(dis, 0x3f, sizeof(dis));
    long long ans = 0;
    dis[scc[0]] = 0;
    q.push(scc[0]);
    while (!q.empty()) {
      int u = q.front();
      q.pop();
      ans += dis[u];
      for (int i = G.heads[u]; i; i = G.e[i].nxt) {
        int v = G.e[i].v;
        if (dis[v] > G.e[i].c) {
          dis[v] = G.e[i].c;
        }
        if (!(--in[v])) {
          q.push(v);
        }
      }
    }
    printf("%lld\n", ans);
    memset(dfn, 0, sizeof(dfn));
    memset(scc, 0, sizeof(scc));
    memset(low, 0, sizeof(low));
    memset(ins, 0, sizeof(ins));
    while (!stk.empty()) stk.pop();
    memset(E.heads, 0, sizeof(E.heads));
    memset(G.heads, 0, sizeof(G.heads));
    E.e_cnt = 0, G.e_cnt = 0, cnt = 0, tot = 0;
  }
  return 0;
}